package com.scau.os.fileSystem.FolderTree;

import java.util.List;

import com.scau.os.fileSystem.directory.Directory;
import com.scau.os.fileSystem.directory.DirectoryEntry;
import com.scau.os.fileSystem.directory.File;

import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;

public class FolderTreeItem extends TreeItem<DirectoryEntry> {
	private boolean isLoaded; // 节点是否已经加载过

	public FolderTreeItem(DirectoryEntry directoryEntry) {
		super(directoryEntry);
		isLoaded = false;
	}

	/**
	 * 预先加载根节点下的所有子节点
	 * 
	 * @throws Exception
	 */
	public void preLoad() throws Exception {
		loadChildren();

		for (TreeItem<DirectoryEntry> child : this.getChildren()) {
			((FolderTreeItem) child).loadChildren();
		}
	}

	/**
	 * 加载当前节点下的所有子节点
	 * 
	 * @throws Exception
	 */
	public void loadChildren() throws Exception {
		if (isLoaded == true) {
			return;
		}
		isLoaded = true;

		if (this.getValue().isFile()) {
			return;
		}

		List<File> childFile = ((Directory) this.getValue()).getAllFiles();
		for (File file : childFile) {
			FolderTreeItem folderTreeItem = new FolderTreeItem(file); // 创建新的FolderTreeItem
			this.getChildren().add(folderTreeItem); // 将新的FolderTreeItem添加到当前节点中
		}

		List<Directory> childDirectory = ((Directory) this.getValue()).getAllDirectories();
		for (Directory directory : childDirectory) {
			FolderTreeItem folderTreeItem = new FolderTreeItem(directory); // 创建新的FolderTreeItem

			// 添加展开事件监听器，当节点展开时递归加载子节点
			folderTreeItem.addEventHandler(FolderTreeItem.branchExpandedEvent(),
					new EventHandler<TreeItem.TreeModificationEvent<DirectoryEntry>>() {
						@Override
						public void handle(TreeModificationEvent<DirectoryEntry> event) {
							for (TreeItem<DirectoryEntry> child : event.getSource().getChildren()) { // 递归加载子节点
								try {
									((FolderTreeItem) child).loadChildren();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
					});

			this.getChildren().add(folderTreeItem); // 将新的FolderTreeItem添加到当前节点中
		}

	}

	public boolean isLoaded() {
		return isLoaded;
	}

	public void setLoaded(boolean isLoaded) {
		this.isLoaded = isLoaded;
	}

}
